<?php
namespace BLL\DAO;

use Illuminate\Support\Facades\Artisan as Artisan;
use Illuminate\Support\Facades\File as File;

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class MigrationBuilder {   
    private static $file_name="";
    public static function createMigration($param_name){
        $jsonObj= self::readFromFile($param_name);
        $tableName = $jsonObj['realTableName']; 
        Artisan::call('migrate:make', array('name'=>$tableName));
        $contents = self::findFile($tableName);
        $up_methods = self::createUp($jsonObj['divs'],$jsonObj['values']);
        $split_content = explode("//", $contents);
        $up_methods ="Schema::create('{$tableName}', function(\$table){ \r\$table->engine = 'InnoDB'; ".implode($up_methods,"")."});\n\t";
        $down_methods ="Schema::drop('{$tableName}');";
        self::contentReplace($split_content,$up_methods,$down_methods);        
        Artisan::call('migrate', ['--database' => 'mysql', '--force' => true]);
        return true;
    }
    
    private static function readFromFile($configName=null){
        $path = str_replace("\\", DIRECTORY_SEPARATOR, $GLOBALS["AppConfig"]["parameter"]);
        $path = str_replace("/", DIRECTORY_SEPARATOR, $path); 
        if (!strrchr($path, DIRECTORY_SEPARATOR)) {
            $path = $path . DIRECTORY_SEPARATOR;
        }
        $filename= \app_path()."\\".$path.$configName.".json";
        echo $filename."<br>";
            if(file_exists($filename)){
                $str = file_get_contents($filename);
                $jsonObject = json_decode($str,true);
                return $jsonObject;
            }
        }
    
    private static function findFile($table_name){
        $filelist = File::files(base_path().'\app\database\migrations');
        for($i=0;$i<sizeof($filelist);$i++){
            $filelist[$i] = str_replace("/", DIRECTORY_SEPARATOR, $filelist[$i]); 
            if(strpos($filelist[$i],$table_name.".php")!==false){
                $multi_file[] = $filelist[$i];
                $contents = File::get($filelist[$i]);
                self::$file_name = $filelist[$i];
            }
        }
        $number_of_file = sizeof($multi_file);
        $contents = File::get(self::$file_name);
        if(($number_of_file)!=1){
            for($i=0;$i<$number_of_file-1;$i++)
            {
                File::delete($multi_file[$i]);
            }
        }
       return $contents;
    } 
        
    private static function contentReplace($split_content,$up,$down){
        file_put_contents(self::$file_name,$split_content[0].$up.$split_content[1].$down.$split_content[2]);
    }
    
    private static function createUp($div,$value){
        for($i=0;$i<sizeof($div);$i++){
            $div_coloum_name['col'][] = $div[$i]['name'];
            $div_coloum_type['col'][] = self::dataTypeReplace($div[$i]['dataType']);
            
        }
        for($i=0;$i<sizeof($value);$i++){
            $div_coloum_name['val'][] = $value[$i]['name'];
            $div_coloum_type['val'][] = self::dataTypeReplace($value[$i]['dataType']);
           
        }
      
        $sample = "\$table->code;";
        for($i=0;$i<sizeof($div_coloum_name['col']);$i++){
           $up_contents[] = str_replace("code","{$div_coloum_type['col'][$i]}('{$div_coloum_name['col'][$i]}')",$sample);
        }
        for($i=0;$i<sizeof($div_coloum_name['val']);$i++){
            $up_contents[] = str_replace("code","{$div_coloum_type['val'][$i]}('{$div_coloum_name['val'][$i]}')",$sample);
        }              
       return $up_contents;
    }
      
    
    private static function dataTypeReplace($string){
        switch ($string) {
        case "Int":
            return "integer";
        case "Bool":
            return "boolean";
        case "String":
            return "string";
        case "Currency":
            return "double";
        case "Date":
            return "date";
        case "DateTime":
            return "dateTime";
        case "Time":
            return "dateTime";
        case "Text":
            return "longText";
        case "BigInt":
            return "bigInteger";
        }
        
    }
    
        
}

